<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use App\Filters\MenuFilter;
use App\Http\Requests\MenuRequest;
use App\Http\Resources\MenuCollection;
use App\Http\Resources\MenuResource;
use App\Models\Menu;
use App\Services\MenuService;
use App\Services\TreeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 菜单模块
 * Class MenuController
 * @package App\Http\Controllers
 */
class MenuController extends Controller
{

    /**
     * 列表
     * @param MenuFilter $filter
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(MenuFilter $filter)
    {
        $filter = Menu::filter($filter)->get();
        $collection = MenuCollection::make($filter)->except(['permission_ids', 'role_permission_config'])->toArray(null);
        $items = TreeService::make($collection['items']);
        return $this->success('', ['items' => $items, 'total' => count($collection['items'])]);
    }

    /**
     * 添加
     * @param MenuRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(MenuRequest $request)
    {
        $data = $request->validate('store');
        DB::beginTransaction();
        try {
            MenuService::updateOrCreate(null, $data);
            DB::commit();
            return $this->successStored();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorStored();
        }
    }

    /**
     * 查看
     * @param Menu $menu
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Menu $menu)
    {
        $menu = MenuResource::make($menu)->except(['created_at', 'updated_at', 'role_permission_config', 'permission_items'])->toArray(null);
        return $this->success('', $menu);
    }

    /**
     * 更新
     * @param MenuRequest $request
     * @param Menu $menu
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(MenuRequest $request, Menu $menu)
    {
        $data = $request->validate('update');
        DB::beginTransaction();
        try {
            MenuService::updateOrCreate($menu, $data);
            DB::commit();
            return $this->successUpdated();
        } catch (\Exception $e) {
            DB::rollback();
            return $e->getMessage();
            return $this->exception($e->getMessage())->errorUpdated();
        }
    }

    /**
     * 删除
     * @param Menu $menu
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Menu $menu)
    {
        DB::beginTransaction();
        try {
            $subMenu = Menu::where('parent_id', '=', $menu->id)->first();
            // 菜单存在下级则禁止删除
            if ($subMenu) {
                return $this->error(__('menu.prohibit_delete_with_subs'));
            }
            $menu->delete();
            DB::commit();
            return $this->successDestoryed();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorDestoryed();
        }
    }

    /**
     * 更新状态
     * @param MenuRequest $request
     * @param Menu $menu
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateStatus(MenuRequest $request, Menu $menu)
    {
        $data = $request->validate('updateStatus');
        if (!$menu->update($data)) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 更新排序
     * @param MenuRequest $request
     * @param Menu $menu
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateSort(MenuRequest $request, Menu $menu)
    {
        $data = $request->validate('updateSort');
        if (!$menu->batchUpdate($data['sort'])) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 上一级选择菜单树
     * @param $id // 当前菜单id
     * @return \Illuminate\Http\JsonResponse
     */
    public function parentTreeConfig($id)
    {
        return $this->success('', MenuService::getParentTree($id));
    }


    /**
     * 获取角色管理模块中的菜单权限列表选项
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleMenuConfig()
    {
        $menu = Menu::orderBy('sort', 'asc')->orderBy('id', 'desc')->get();
        $collection = MenuCollection::make($menu)->only(['id', 'name', 'parent_id', 'role_permission_config'])->toArray(null);
        $items = TreeService::make($collection['items']);
        return $this->success('', ['items' => $items, 'total' => count($collection['items'])]);
    }

    /**
     * 登录管理员的菜单配置
     * @return \Illuminate\Http\JsonResponse
     */
    public function userMenuConfig()
    {
        return $this->success('', ['items' => MenuService::getLoginUserMenu()]);
    }
}
